import { reactive, ref } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import { 
    type BusinessModelQueryParams, 
    type BusinessModelInfo, 
    type BusinessModelSave, 
    type BusinessModelItemQueryParams,
    type BusinessModelItemSave,
    type BusinessModelItemInfo,
    type SelectOption
 } from "@/types";
import { de } from "element-plus/es/locales.mjs";
import useCommon from "./useCommon";

export default function() {
    let insertBusinessModelWindowEnable = ref(false)
    let updateBusinessModelWindowEnable = ref(false)
    let businessModelItemWindowsEnable = ref(false)
    let insertBusinessModelItemWindowEnable = ref(false)
    let updateBusinessModelItemWindowEnable = ref(false)
    let businessModelCurrentPage = ref(1)
    let businessModelPageSize = ref(10)
    let modelItemCurrentPage = ref(1)
    let modelItemPageSize = ref(10)
    let businessModelQueryParam = reactive<BusinessModelQueryParams>({
        modelName: '',
        modelKey: '',
        isEnable: 0
    });
    let businessModelItemQueryParam = reactive<BusinessModelItemQueryParams>({
        modelKey: '',
        fieldName: '',
        fieldKey: '',
        isEnable: 0
    })
    let businessModelInsert = reactive<BusinessModelSave>({
        id: '',
        modelName: '',
        modelKey: '',
        description: '',
        isEnable: 0
    })
    let businessModelUpdate = reactive<BusinessModelSave>({
        id: '',
        modelName: '',
        modelKey: '',
        description: '',
        isEnable: 0
    })
    let businessModelInfoList = reactive<BusinessModelInfo[]>([])
    let businessModelItemInsert = reactive<BusinessModelItemSave>({
        id: '',
        modelKey: '',
        fieldName: '',
        fieldKey: '',
        fieldValueType: 'basicType',
        fieldType: '',
        description: '',
        isEnable: 0
    })
    let businessModelItemUpdate = reactive<BusinessModelItemSave>({
        id: '',
        modelKey: '',
        fieldName: '',
        fieldKey: '',
        fieldValueType: '',
        fieldType: '',
        description: '',
        isEnable: 0
    })
    let businessModelItemInfoList = reactive<BusinessModelItemInfo[]>([
        {
            id: '234',
            modelKey: 'item1',
            fieldName: '明细1',
            fieldKey: '2',
            fieldValueType: '4',
            fieldType: '5',
            description: '而突然第一套房',
            isEnable: 0
        }
    ])
    let businessModelItemWindow = reactive({
        modelKey: '',
        modelName: ''
    })
    const fieldValueTypeList = [
        {
            key: 'basicType',
            value: '基础类型'
        },
        {
            key: 'enumConstant',
            value: '常量类型'
        },
        {
            key: 'customType',
            value: '自定义类型'
        }
    ] 
    let filedTypeList = reactive<SelectOption[]>([])
    let enumConstantOptionList = reactive<SelectOption[]>([])
    let basicTypeOptionList = reactive<SelectOption[]>([])
    let businessModelOptionList = reactive<SelectOption[]>([])
    async function searchBusinessModelByQueryParam(params:BusinessModelQueryParams) {
        console.log('查询业务模型')   
        let result = await axios.post("/businessModel/select/byQuery", params).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                businessModelInfoList.length = 0
                Object.assign(businessModelInfoList, res.data.content)
                // 重置分页
                businessModelCurrentPage.value = 1
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                });
            }
        })
    }
    async function insertBusinessModelSubmit() {
        console.log('新增业务模型')
        console.log(JSON.stringify(businessModelInsert))
        // 调用后端接口
        let result = await axios.post("/businessModel/insert", businessModelInsert).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '新增业务模型成功!'
                });
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                });

            }
            return res
        })
        // 刷新列表 
        updateBusinessModelList()
        // 清空insert参数
        clearBusinessModelInsert()
        // 关闭窗口
        insertBusinessModelWindowEnable.value = false
    }
    async function updateBusinessModelList() {
        console.log('更新业务模型列表')
        let result = await axios.post("/businessModel/select/byQuery", businessModelQueryParam).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                businessModelInfoList.length = 0
                Object.assign(businessModelInfoList, res.data.content)
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                });
            }
        })
    }
    function clearBusinessModelInsert() {
        businessModelInsert.modelKey = ''
        businessModelInsert.modelName = ''
        businessModelInsert.description = ''
        businessModelInsert.isEnable = 0
    }
    function getBusinessModelItemInfo(index: number, row: BusinessModelInfo) {
        console.log('获取详情')
        // 打开详情窗口
        businessModelItemWindowsEnable.value = true
        // 参数赋初始值
        businessModelItemQueryParam.modelKey = row.modelKey
        businessModelItemWindow.modelKey = row.modelKey
        businessModelItemWindow.modelName = row.modelName
        businessModelItemInsert.modelKey = row.modelKey
        // 更新明细项列表
        updateBusinessModelItemList()
    }
    async function updateBusinessModelItemList() {
        let result = await axios.post("/modelItem/selectList/byQuery", businessModelItemQueryParam).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                businessModelItemInfoList.length = 0
                Object.assign(businessModelItemInfoList, res.data.content)
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                });
            }
        })
    }
    function updateBusinessModel(index: number, row: BusinessModelSave){
        console.log('更新业务模型')
        // 打开修改业务模型窗口
        updateBusinessModelWindowEnable.value = true
        // 将数据赋值给businessModelUpdate
        Object.assign(businessModelUpdate, row)
    }
    async function updateBusinessModelSubmit() {
        console.log('更新业务模型，调用后端接口')
        console.log(JSON.stringify(businessModelUpdate))
        let result = await axios.post("/businessModel/update", businessModelUpdate).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '修改业务模型成功!'
                });
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                });
            }
        })
        // 清空update参数
        clearBusinessModelUpdate()
        // 关闭窗口
        updateBusinessModelWindowEnable.value = false
        // 刷新列表
        updateBusinessModelList()
    }
    function clearBusinessModelUpdate() {
        businessModelUpdate.id = ''
        businessModelUpdate.modelKey = ''
        businessModelUpdate.modelName = ''
        businessModelUpdate.description = ''
        businessModelUpdate.isEnable = 0
    }
    async function deleteBusinessModel(id: string) {
        console.log('删除业务模型')
        console.log(id)
        let result = await axios.get("/businessModel/delete/" + id).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '删除业务模型成功!'
                });
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                })
            }
        })
        // 更新列表
        updateBusinessModelList()
    }
    async function searchBusinessModelItemByQueryParam() {
        console.log('查询业务模型明细')
        console.log(JSON.stringify(businessModelItemQueryParam))
        businessModelItemQueryParam.modelKey = businessModelItemWindow.modelKey
        let result = await axios.post("/modelItem/selectList/byQuery", businessModelItemQueryParam).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                businessModelItemInfoList.length = 0
                Object.assign(businessModelItemInfoList, res.data.content)
                modelItemCurrentPage.value = 1
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                });
            }
        })
    }
    function insertBusinessModelItem() {
        // 打开窗口
        insertBusinessModelItemWindowEnable.value = true
        businessModelItemInsert.modelKey = businessModelItemWindow.modelKey

    }
    async function updateBusinessModelItem(index: number, row: BusinessModelItemInfo) {
        console.log('更新业务模型明细')
        // 打开窗口
        updateBusinessModelItemWindowEnable.value = true
        // 初始化数据
        Object.assign(businessModelItemUpdate, row)
    }
    async function deleteBusinessModelItem(id: string) {
        console.log('删除业务模型明细')
        console.log(id)
        let result = await axios.get("/modelItem/delete/" + id).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '删除业务模型明细成功!'
                });
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                })
            }
        })
        // 更新列表
        updateBusinessModelItemList()
    }
    async function insertBusinessModelItemSubmit() {
        console.log('新增业务模型明细')
        console.log(JSON.stringify(businessModelItemInsert))
        let result = await axios.post("/modelItem/insert", businessModelItemInsert).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '新增业务模型明细成功!'
                });
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                });
            }
        })
        // 清空参数
        clearBusinessModelItemInsert()
        // 关闭窗口
        insertBusinessModelItemWindowEnable.value = false
        // 更新列表
        updateBusinessModelItemList()
    }
    function clearBusinessModelItemInsert() {
        businessModelItemInsert.fieldKey = ''
        businessModelItemInsert.fieldName = ''
        businessModelItemInsert.fieldType = ''
        businessModelItemInsert.fieldValueType = ''
        businessModelItemInsert.description = ''
        businessModelItemInsert.isEnable = 0
    }
    async function updateBusinessModelItemSubmit() {
        console.log('修改业务模型明细')
        console.log(JSON.stringify(businessModelItemUpdate))
        let result = await axios.post("/modelItem/update", businessModelItemUpdate).then(res => {
            console.log(res)
            if (res.data.code == 200) {
                ElMessage({
                    type: 'success',
                    message: '修改业务模型明细成功!'
                });
            } else {
                ElMessage({
                    type: 'error',
                    message: res.data.msg
                })
            }
        })
        // 清空参数
        clearBusinessItemUpdate()
        // 关闭窗口
        updateBusinessModelItemWindowEnable.value = false
        // 更新列表
        updateBusinessModelItemList()
    }
    function clearBusinessItemUpdate() {
        Object.assign(businessModelItemUpdate, {
            id: '',
            modelKey: '',
            fieldName: '',
            fieldKey: '',
            fieldValueType: '',
            fieldType: '',
            description: '',
            isEnable: 0
        })
    }
    function getFieldValutType(param: string): string {
        const option = fieldValueTypeList.find(option => option.key === param);
        return option ? option.value : '';
    }
    function handleFieldValueTypeChangeEvent(param: any) {
        console.log('fieldValueTypeChangeEvent')
        console.log(JSON.stringify(param))
        // 清空fieldType选择框的值
        businessModelItemInsert.fieldType = ''
        // 联动变更filedTypeList
        switch (param) {
            case 'basicType':
                filedTypeList.length = 0
                Object.assign(filedTypeList, basicTypeOptionList)
                break;
            case 'enumConstant':
                filedTypeList.length = 0
                Object.assign(filedTypeList,  enumConstantOptionList)
                break;
            case 'customType':
                filedTypeList.length = 0
                Object.assign(filedTypeList,  businessModelOptionList)
                break;
            default:
        }
        console.log('变更后filedTypeList')
        // console.log(JSON.stringify(filedTypeList))
        // businessModelItemInsert.fieldType = filedTypeList[0].value
    }
    function loadFieldTypeList() {
        console.log('初始化基础类型')
        basicTypeOptionList.length = 0
        Object.assign(basicTypeOptionList, getBasicType())
        console.log('初始化常量类型')
        enumConstantOptionList.length = 0
        Object.assign(enumConstantOptionList, getEnumConstantOptionList())
        console.log('初始化自定义类型')
        businessModelOptionList.length = 0
        Object.assign(businessModelOptionList, getBusinessModelOptionList())
        // 设置默认项
        Object.assign(filedTypeList, basicTypeOptionList)
    }
    // 获取基础类型集合
    function getBasicType():SelectOption[] {
        return [
            {
                key: 'string',
                value: '字符串'
            },
            {
                key: 'integer',
                value: '整型数'
            },
            {
                key: 'double',
                value: '浮点数'
            },
            {
                key: 'long',
                value: '长整型数'
            },
            {
                key: 'boolean',
                value: '布尔值'
            },
            {
                key: 'date',
                value: '日期'
            },
            {
                key: 'bigDecimal',
                value: '金额'
            },
            {
                key: 'collection',
                value: '集合'
            }
        ]
    }
    // 获取枚举常量option集合
    async function getEnumConstantOptionList() {
        try {
            let result = await axios.get("/enumConstant/get/all/enumConstant/options");
            // console.log(JSON.stringify(result))
            if (result.data.code == 200) {
                enumConstantOptionList.length = 0
                Object.assign(enumConstantOptionList, result.data.content)
                // console.log(JSON.stringify(result.data.content))
            }
        } catch (error) {
            console.log(error)
        }
    }
    // 获取自定义类型option集合
    async function getBusinessModelOptionList() {
        try {
            let result = await axios.get("/businessModel/get/all/businessModel/options");
            console.log('获取自定义类型option集合')
            console.log(JSON.stringify(result))
            if (result.data.code == 200) {
                businessModelOptionList.length = 0
                Object.assign(businessModelOptionList, result.data.content)
                console.log(JSON.stringify(result.data.content))
            }
        } catch (error) {
            console.log(error)
        }
    }
    // 自动补全框查询函数
    function autoCompleteQuerySearch(queryString: string, cb: any) {
        console.log('自动补全框查询函数')
        let results = queryString
        ? filedTypeList.filter(autoCompleteFilter(queryString))
        : filedTypeList
        // call callback function to return suggestions
        cb(results)
    }
    // 自动补全框过滤函数
    function autoCompleteFilter(queryString: string) {
        return (selectOption: SelectOption) => {
            return (
                selectOption.key.toLowerCase().indexOf(queryString.toLowerCase()) === 0
            )
        }
    }
    // 自动补全框选择事件
    function autoCompleteHandleSeletct(item: Record<string, any>) {
        console.log('autoCompleteHandleSeletct')
        console.log(JSON.stringify(item))
        if (insertBusinessModelItemWindowEnable.value) {
            businessModelItemInsert.fieldType = item.key
        } else if (updateBusinessModelItemWindowEnable.value) {
            businessModelItemUpdate.fieldType = item.key
        }
    }
    // 自动补全框处理事件函数
    function actoCompleteHandleIconClick(event: Event) {
        console.log('actoCompleteHandleIconClick')
        console.log(event)
    }
    // 业务模型分页处理页码
    function businessModelHandleCurrentChange(param: number) {
        businessModelCurrentPage.value = param
    }
    // 业务模型处理每页条数变化
    function businessModelHandleSizeChange(param: number) {
        businessModelPageSize.value = param
        businessModelCurrentPage.value = 1
    }
    // 明细项分页处理页码
    function modelItemHandleCurrentChange(param: number) {
        modelItemCurrentPage.value = param
    }
    // 明细项处理每页条数变化
    function modelItemHandleSizeChange(param: number) {
        modelItemPageSize.value = param
        modelItemCurrentPage.value = 1
    }
    return {
        insertBusinessModelWindowEnable,
        updateBusinessModelWindowEnable,
        businessModelItemWindowsEnable,
        insertBusinessModelItemWindowEnable,
        updateBusinessModelItemWindowEnable,
        businessModelQueryParam,
        businessModelInsert,
        businessModelUpdate,
        businessModelInfoList,
        businessModelItemQueryParam,
        businessModelItemWindow,
        businessModelItemInsert,
        businessModelItemUpdate,
        businessModelItemInfoList,
        fieldValueTypeList,
        filedTypeList,
        enumConstantOptionList,
        basicTypeOptionList,
        businessModelOptionList,
        businessModelCurrentPage,
        businessModelPageSize,
        modelItemCurrentPage,
        modelItemPageSize,
        searchBusinessModelByQueryParam,
        getBusinessModelItemInfo,
        updateBusinessModel,
        deleteBusinessModel,
        insertBusinessModelSubmit,
        updateBusinessModelSubmit,
        searchBusinessModelItemByQueryParam,
        insertBusinessModelItem,
        updateBusinessModelItem,
        deleteBusinessModelItem,
        insertBusinessModelItemSubmit,
        updateBusinessModelItemSubmit,
        getFieldValutType,
        loadFieldTypeList,
        handleFieldValueTypeChangeEvent,
        autoCompleteQuerySearch,
        autoCompleteHandleSeletct,
        actoCompleteHandleIconClick,
        businessModelHandleSizeChange,
        businessModelHandleCurrentChange,
        modelItemHandleCurrentChange,
        modelItemHandleSizeChange
    }
}